﻿using System.Diagnostics;
using System.IO;
using Whisper.net;

namespace SpeedRecognition
{
    internal class WhisperManager
    {
        private WhisperManager() { }

        public static WhisperManager Instance { get; } = new();

        WhisperFactory? _whisperFactory;
        WhisperProcessor? _processor;
        public void Init()
        {   //ggml-distil-small.en    ggml-model-whisper-tiny.en.bin
            _whisperFactory = WhisperFactory.FromPath("ggml-base.bin");
            _processor = _whisperFactory.CreateBuilder().WithLanguage("en").Build();
        }

        public Action<TimeSpan, TimeSpan, string> WriteWhisperInfo { get; set; }

        public async void ReadFile(string filePath)
        {
            if (_processor == null)
                return;

            await using var fileSteam = File.OpenRead(filePath);
            {
                await foreach (SegmentData segment in _processor.ProcessAsync(fileSteam))
                {
                    WriteWhisperInfo(segment.Start, segment.End, segment.Text);
                }
            }
        }

        public async void ReadData(byte[] data)
        {
            if (_processor == null)
                return;

            using MemoryStream memoryStream = new MemoryStream(data);
            await foreach (SegmentData segment in _processor.ProcessAsync(memoryStream))
            {
                WriteWhisperInfo(segment.Start, segment.End, segment.Text);
                //Debug.WriteLine(segment.Text);
            }
        }
 
    }
}
